﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ChEngine
{
    public class Perft
    {
        IBitBoard board;
        IMoveGenerator generator;
        int[] moves = new int[1000];
        public Perft(IBitBoard board,IMoveGenerator generator)
        {
            this.board = board;
            this.generator = generator;
        }
        public PerfResults DoPerft(int depth)
        {
            Stopwatch sw = new Stopwatch();
            PerfResults perft = new PerfResults();
            sw.Start();
            perft.MovesCount = InternalPerft(depth, board, generator, 0);
            sw.Stop();
            perft.Elapsed = (ulong)sw.ElapsedMilliseconds;
            return perft;
        }
        private unsafe ulong InternalPerft(int depth, IBitBoard b, IMoveGenerator generator,int index)
        {
            if (depth == 0)
            {
                return 1;
            }
            ulong count = 0;
            int moveCount = generator.GetMoves(b, moves, index,MoveGenerationMode.All);
            //ICollection<BitMove> moves = BitBoard.GetMoves(b.ToMove, b);
            for (int i = index; i < index+moveCount; ++i)
            {
               
                if (generator.IsMoveLegal(b,moves[i]) )
                {
                    Side moving = b.ToMove;
                    b.DoMove(moves[i]);
                    if (generator.InCheck(b,moving))
                    {
                        b.UndoMove(moves[i]);
                        continue;
                    }
                    count += InternalPerft(depth - 1, b, generator, index+moveCount);
                    b.UndoMove(moves[i]);
                    
                }
            }
            return count;
        }

    }
}
